package middle

import (
	"chart.zozoo.net/app/utils/jwt"
	"chart.zozoo.net/app/utils/rsp"
	"github.com/gin-gonic/gin"
	"strings"
)

// Auth 用户认证
func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("Authorization")
		if token == "" {
			token = c.Request.URL.Query().Get("Authorization")
		}
		
		if token == "" {
			rsp.JsonErr(c, rsp.SetMsg("no Authorization"), rsp.SetCode(401))
			c.Abort()
		} else {

			token = strings.Replace(token, "Bearer ", "", 1)

			//验证token
			uuid, err := jwt.ValidateToken(token)
			if err != nil {
				rsp.JsonErr(c, rsp.SetMsg(err.Error()), rsp.SetCode(401))
				c.Abort()
			} else {
				c.Set("uuid", uuid)
				c.Next()
			}
		}
	}
}
